<template>
    <div class="common-search-result">
        <div class="music-search-result search-result-part">
            <div class="title">
                <h2>歌曲</h2>
                <div class="tools">
                    <n-button text @click="playAll"> 播放全部 </n-button>
                </div>
            </div>
            <song-item
                v-for="(song, index) of songSearchResult"
                :key="song.id"
                :song="song"
                :index="index"
                :type="SONG_ITEM_TYPE.LARGE"
                @click="playThisSong(song)"
                play-on-click
            ></song-item>
        </div>
    </div>
</template>
<script setup lang="ts">
import { ref, Ref, watch } from "vue";
import { selectSongPageData } from "@/api/modules/song";
import { useRoute } from "vue-router";
import { ISongItem } from "@/types/song-item";
import SongItem from "@/components/song-item.vue";
import { AxiosResponse } from "axios";
import { SONG_ITEM_TYPE } from "@/constant/song";
import { useStore } from "vuex";
import { NButton } from "naive-ui";

const store = useStore();
const route = useRoute();

const keywords: Ref<string> = ref("");
const songSearchResult: Ref<Array<ISongItem>> = ref([]);

const playThisSong = function (song: ISongItem) {
    store.dispatch("play/updatePlayingInfo", song);
};

const searchInMusic = function () {
    selectSongPageData({
        _end: 30,
        _order: "ASC",
        _sort: "title",
        _start: 0,
        title: keywords.value,
    }).then((res: AxiosResponse) => {
        songSearchResult.value = res.data;
    });
};

watch(
    route,
    function () {
        keywords.value = route.query.keyword as string;
        if (keywords.value) {
            searchInMusic();
        }
    },
    { immediate: true }
);

const playAll = () => {
    // 添加到待播放列表
    store.dispatch("play/add2ReadyList", songSearchResult.value);
    // 竞选当前播放的歌曲
    store.dispatch("play/updatePlayingInfo", songSearchResult.value[0]);
};
</script>

<style lang="less" scoped>
.common-search-result {
    padding: 0 30px;
    .search-result-part {
        margin-bottom: 20px;
        .title {
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
    }
}
</style>
